<?php

namespace app\index\controller;

use think\exception\ValidateException;
use app\model\Member;
use app\model\Users;
use app\model\Agent;
use app\model\Curl;
use app\model\WxBizDataCrypt;
use app\model\Config;
use app\model\CouponReceive;
use app\model\Technical;
use app\model\Wxmini;
use app\model\Openid;
use app\model\OrderStaff;


use EasyWeChat\Factory;

class MemberController extends Base
{
	public function detail()
	{
		$this->updatanickname();
		$Membermob = new Member;
		$memberinfo = $Membermob->getUserByWechat();

		$memberinfo['is_agent'] = (int) $memberinfo['is_agent'];

		$user_id = $memberinfo['id'];
		if ($memberinfo['primaryuid']) {
			$user_id = $memberinfo['primaryuid'];
		}

		$user = Users::getuserbyuid($user_id);

		if (!empty($user)) {
			$memberinfo['is_user'] = 1;
		} else {
			$memberinfo['is_user'] = 0;
		}
		if (!empty($user['sid'])) {
			$memberinfo['is_storeadmin'] = 1;
		} else {
			$memberinfo['is_storeadmin'] = 0;
		}

		$Agent = Agent::where(['weid' => weid(), 'uid' => $user_id])->find();
		if (!empty($Agent)) {
			$memberinfo['agent'] = $Agent->toArray();
		} else {
			$memberinfo['agent']['income'] = 0;
		}

		$Technical = Technical::where(['weid' => weid(), 'uid' => $user_id])->find();
		if (!empty($Technical)) {
			$Technical = $Technical->toArray();
		}

		if (!empty($Technical)) {
			$memberinfo['is_technical'] = $Technical['status'];
		} else {
			$memberinfo['is_technical'] = 0;
		}

		if ($memberinfo['nickname'] == '微信用户' || $memberinfo['nickname'] == '匿名用户') {
			$memberinfo['nickname'] = "";
		}

		$memberinfo['coupon'] = (int) CouponReceive::where(['weid' => weid(), 'uid' => $memberinfo['uid']])->count();

		$memberinfo['sex'] = sex($memberinfo['sex']);

		if (input('get.v') == Config::getconfig()['program_version']) {
			$memberinfo['is_audit'] = 1;
		} else {
			$memberinfo['is_audit'] = 0;
		}

		$data = $memberinfo;

		return $this->json(['data' => $data]);
	}

	public function getkefuurl()
	{
		$orderid = input('get.orderid');

		$technicalId = OrderStaff::getuuid($orderid);
		$Membermob = new Member;
		$memberinfo = $Membermob->getUserByWechat();
		$data['url'] = gethost() . TP_APIURL . '/h5-im?toid=' . Openid::getMpOpenidbyuuid($technicalId) . '&uid=' . $memberinfo['id'] . '&xmtoken=' . $this->getToken();

		return $this->json(['data' => $data]);
	}
	public function getsetmpurl()
	{
		$Membermob = new Member;
		$memberinfo = $Membermob->getUserByWechat();

		$data['url'] = gethost() . TP_APIURL . '?s=/index/member/setmpopenid&xmtoken=' . $this->getToken() . '&uid=' . $memberinfo['id'];

		return $this->json(['data' => $data]);
	}

	public function setmpopenid()
	{
		$weid = weid();
		$openid = input('get.openid');

		$backurl = gethost() . $_SERVER["SCRIPT_NAME"] . '?s=/index/member/setmpopenid&xmtoken=' . $this->getToken() . '&uid=' . input('get.uid');
		if (empty($openid)) {
			$url = gethost() . $_SERVER["SCRIPT_NAME"] . '?s=/index/wechatmp/getopenid&xmtoken=' . $this->getToken() . '&uid=' . input('get.uid') . '&backurl=' . urlencode($backurl);
			return redirect($url);
		} else {
			$uid = input('get.uid');
			if (empty(Openid::where(['weid' => $weid, 'ptype' => 'mp', 'openid' => $openid])->find())) {
				Openid::create([
					'weid' => $weid,
					'ptype' => 'mp',
					'uid' => $uid,
					'openid' => $openid
				]);
			}
		}
		echo <<< EOT
			<!DOCTYPE html>
			<html lang="zh-cmn-Hans">
			<head>
				<meta charset="UTF-8">
				<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0,viewport-fit=cover">
				<title>绑定公众号信息提醒</title>
				<link rel="stylesheet" href="static/style/weui.css"/>
			</head>
			<body ontouchstart data-weui-mode="care" >
				<div class="weui-msg">
					<div class="weui-msg__icon-area"><i class="weui-icon-success weui-icon_msg"></i></div>
					<div class="weui-msg__text-area">
						<h2 style="text-align: center;" class="weui-msg__title">设置成功</h2>
					</div>
				</div>
			</body>
			</html>
EOT;
	}

	public function openid()
	{
		$code = input('get.code');

		if ($code) {
			$app = Wxmini::make();
			$data = $app->auth->session($code);
			$data['ptype'] = 'wxapp';
			$data['sessionid'] = md5(uniqid());
		} else {
			$data = $this->userInfo;
		}
		$data['sessionid'] = md5(uniqid());
		$data['weid'] = weid();

		$this->setToken($data, $data['sessionid']);

		return $this->json(['data' => $data]);
	}
	public function check()
	{
		if ($this->userInfo['openid']) {
			$errno = 0;
		} else {
			$errno = 1;
		}

		return $this->json(['errno' => $errno, 'data' => $this->userInfo]);
	}
	public function userinfo()
	{
		return $this->json(['data' => $this->userInfo]);
	}

	public function getuid()
	{
		$data['uid'] = UID();
		return $this->json(['data' => $data]);
	}

	//获取用户手机号
	public function getsessionkey()
	{
		global $_GPC;

		$code = $_GPC['code'];
		$account = pdo_get('account_wxapp', array('uniacid' => weid()));
		$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $account['key'] . '&secret=' . $account['secret'] . '&js_code=' . $code . '&grant_type=authorization_code';

		$curl = new Curl();
		$curl->setOpt(CURLOPT_SSL_VERIFYPEER, false);
		$curl->get($url);
		$result = json_decode($curl->response, true);
		return $this->json(['data' => $result]);
	}

	public function updatanickname()
	{
		$postdata['nickname'] = input('post.nickName');
		$postdata['userpic'] = input('post.avatarUrl');

		if (empty($postdata['nickname'])) {
			$postdata['nickname'] =  $this->userInfo['nickname'];
		}

		if (empty($postdata['userpic'])) {
			$postdata['userpic'] =  $this->userInfo['avatar'];
		}

		if (!empty($postdata['nickname'])) {
			Member::where('id', UID())->update($postdata);
		}
	}
	public function bindmobile()
	{
		$app = Wxmini::make();
		$code = input('post.code');
		$iv = input('post.iv');
		$encryptedData = input('post.encryptedData');
		$data = $app->auth->session($code);
		if (!isset($data['session_key'])) {
			return $this->json(['msg' => '获取手机号码失败！状态码：' . $data['errcode'], 'errno' => 1]);
		}
		$decryptedData = $app->encryptor->decryptData($data['session_key'], $iv, $encryptedData);
		Member::update(['id' => UID(), 'telephone' => $decryptedData['phoneNumber']]);
		return $this->json(['data' => $decryptedData['phoneNumber']]);
	}
	// public function bindmobile()
	// {
	// 	global $_GPC, $_W;

	// 	$uid           = UID(); 
	// 	$encryptedData = $_GPC['encryptedData'];
	// 	$iv            = $_GPC['iv'];
	// 	$sessionKey    = $_GPC['session_key'];
	// 	$appid = $_W['account']['key'];

	// 	$pc = new WxBizDataCrypt($appid, $sessionKey);
	// 	$errCode = $pc->decryptData($encryptedData, $iv, $data);
	// 	if ($errCode == 0) {
	// 		$phone = json_decode($data, 'true');

	// 		Member::update(['id' => UID(), 'telephone' => $phone['phoneNumber']]);

	// 		return $this->json(['data' => $phone]);
	// 	} else {
	// 		return $this->json(['errno' => 1, 'data' => ['errcode' => $errCode, 'appid' => $appid]]);
	// 	}
	// }

	public function bindpid()
	{
		$pid = input('post.pid');

		if (empty($pid)) {
			$pid = input('get.pid');
		}

		if (!empty($pid) && !empty(UID())) {
			$Membermob = new Member;
			$memberinfo = $Membermob->getUserByWechat();

			if (empty($memberinfo['pid'])) {
				if ($memberinfo['id'] != $pid) {
					Member::where('id', UID())->update(['pid' => $pid]);
				}
			}
		}
		return $this->json(['data' => $memberinfo]);
	}

	public function team()
	{
		$data['first'] = Member::field('id,nickname,regdate,userpic')
			->where(['weid' => weid(), 'pid' => UID()])
			->select()
			->toArray();

		if (!empty($data['first'])) {
			foreach ($data['first'] as &$vo) {
				$vo['regdate'] = time_format($vo['regdate']);

				if (empty($pid)) {
					$pid = $vo['id'];
				} else {
					$pid = $pid . ',' . $vo['id'];
				}
			}
			$pidin = explode(',', $pid);

			$data['second'] = Member::field('id,nickname,regdate,userpic')
				->where(['weid' => weid(), 'pid' => $pidin])
				->select()
				->toArray();

			foreach ($data['second'] as &$vo) {
				$vo['regdate'] = time_format($vo['regdate']);
			}
		}

		return $this->json(['data' => $data]);
	}

	public function agent()
	{
		$user = Users::getuserbyuid(PUID());
		$data = Agent::field('id,uid,name,tel')
			->where(['weid' => weid(), 'uid' => $user['id']])
			->select()
			->toArray();

		return $this->json(['data' => $data]);
	}

	public function update()
	{
		$uid = UID();
		$postdata = input('post.');

		if (!empty($postdata['userpic'])) {
			$data['userpic'] = $postdata['userpic'];
		}

		if (!empty($postdata['nickname'])) {
			$data['nickname'] = $postdata['nickname'];
		}
		if (!empty($postdata['birthday'])) {
			$data['birthday'] = $postdata['birthday'];
		}
		if (!empty($postdata['sex'])) {

			if ($postdata['sex'] == '男') {
				$data['sex'] = 1;
			} elseif ($postdata['sex'] == '女') {
				$data['sex'] = 2;
			} else {
				$data['sex'] = 0;
			}
		}
		$data['id'] = $uid;
		Member::update($data);
		return $this->json(['data' => $data]);
	}
	public function login()
	{
		$Configdata = Config::getconfig('common');
		$Membermob = new Member;
		$memberinfo = $Membermob->getUserByWechat();
		if ($Configdata['WECHAT_REGISTER_CLOSE'] == 1 && input('get.v') != Config::getconfig()['program_version']) {


			if (!empty($memberinfo['name'])) {
				if (empty($memberinfo['status'])) {
					$data['errno'] = 20001;
					return $this->json(['msg' => '账号审核中', 'data' => $data]);
				}
			} else {
				$data['errno']  = 10001;
				return $this->json(['msg' => '您没还完成注册', 'data' => $data]);
			}
		}
		$data['uid'] = $memberinfo['id'];
		$data['errno'] = 0;
		return $this->json(['data' => $data]);
	}
}
